package cc.telecomdigital.tdstock;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;

public class DeviceIdSharedPrefTools
{
	static final private String LOG_TAG = "SharedPrefTools";
	
	static final private String CONTEXTPACKAGENAME = "cc.telecomdigital.mangopro";
	static final private String DEVICEID_PREFNAME = "cc_share_pref_device_id";
	
	static private SharedPreferences _otherApp_prefs_deviceid;
	static private SharedPreferences _prefs_deviceid;
	
	static final private String PREFS_DEVICE_ID = "prefs_device_id"; 
	static final private int DEVICE_ID_LENGTH = 40; 
	
	static public void Init(Context iContext)
	{
		_prefs_deviceid = iContext.getSharedPreferences(DEVICEID_PREFNAME, Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
		try
		{
			Context otherAppContext;
			otherAppContext = iContext.createPackageContext(CONTEXTPACKAGENAME, Context.CONTEXT_IGNORE_SECURITY);
			_otherApp_prefs_deviceid = otherAppContext.getSharedPreferences(DEVICEID_PREFNAME, Context.MODE_WORLD_READABLE);
		}
		catch (NameNotFoundException e)
		{
			Log.d(LOG_TAG, "NameNotFoundException=>" + e.toString());
			e.printStackTrace();
		}
	}
	
	static public void saveDeviceId(final String deviceId)
	{
		String tmpDeviceId = _prefs_deviceid.getString(PREFS_DEVICE_ID, "");
		if(tmpDeviceId.trim().length() != DEVICE_ID_LENGTH)
		{
			if(_otherApp_prefs_deviceid != null)
				tmpDeviceId = _otherApp_prefs_deviceid.getString(PREFS_DEVICE_ID, "");
			
			Log.d(LOG_TAG, "otherApp_prefs_deviceid=>" + _otherApp_prefs_deviceid + "," + tmpDeviceId);
			
			if(tmpDeviceId.trim().length() != DEVICE_ID_LENGTH)
				tmpDeviceId = deviceId;
			
			_prefs_deviceid.edit().putString(PREFS_DEVICE_ID, tmpDeviceId).commit();
			Log.d(LOG_TAG, "saveDeviceId=>" + tmpDeviceId);
		}
	}
	
	static public String getDeviceId()
	{
		String tmpDeviceId = _prefs_deviceid.getString(PREFS_DEVICE_ID, "");
		if(tmpDeviceId.trim().length() != DEVICE_ID_LENGTH)
		{
			if(_otherApp_prefs_deviceid != null)
				tmpDeviceId = _otherApp_prefs_deviceid.getString(PREFS_DEVICE_ID, "");
			
			if(tmpDeviceId.trim().length() == DEVICE_ID_LENGTH)
				saveDeviceId(tmpDeviceId);
			else
				tmpDeviceId = "";
		}
		return tmpDeviceId;
	}
}
